﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Zadatak5.Tests
{
    class StringCalculator
    {
        private static char[] DEFAULT_SEPARATORS = new char[] { ',', '\n' };

        public int Add(string value)
        {
            if (value.Length == 0)
            {
                return 0;
            }

            char[] separators = determineSeparators(value);
            if (separators.Length > DEFAULT_SEPARATORS.Length)
            {
                value = value.Remove(0, 4);
            }

            string[] strings = extractNumbers(value, separators);
                
            List<int> integers = new List<int>();
            List<int> negatives = new List<int>();
            foreach(string s in strings)
            {
                int i = Convert.ToInt32(s);
                if (i < 0) negatives.Add(i);
                integers.Add(i);
            }

            if (negatives.Count > 0)
            {
                throw new ArgumentException("negatives not allowed: " + string.Join(",", negatives.Select(n => n.ToString()).ToArray()));
            }

            return integers.Sum(i => i);
        }

        private string[] extractNumbers(string numbers, char[] separators)
        {
            string[] strings = numbers.Split(separators);

            if (strings.Length == 0)
            {
                return new string[] { numbers };
            }

            return strings;
        }

        private char[] determineSeparators(string numbers)
        {
            List<char> usedSeparators = new List<char>(DEFAULT_SEPARATORS);

            if (numbers.StartsWith("//") && numbers.Length >= 4)
            {
                usedSeparators.Add(numbers.ElementAt(2));
            }

            return usedSeparators.ToArray();
        }
    }
}
